<template>
  <div class="createCource">
    <incrementCourse @close="close('isShowCreateSource')" />
    <selectSchoolSource @close="close('isShowSelectSource')" />
    <div class="course-top">
      <div class="top-left">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>布置作业</el-breadcrumb-item>
          <el-breadcrumb-item>跟着学</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div @click="back" class="top-right">返回</div>
    </div>
    <div class="course-form">
      <div>
        <el-form ref="ruleForm" :model="form" label-width="8vw" :rules="rules">
          <div class="flexbox">
            <!-- 作业名称 -->
            <div class="box">
              <el-form-item label="作业名称" prop="taskName">
                <el-input
                  maxlength="20"
                  :disabled="form.checkStatus == 1"
                  v-model="form.taskName"
                  placeholder="请输入作业名称"
                  style="width: 20vw"
                ></el-input>
              </el-form-item>
              <el-form-item label="适合人群" prop="gradeId">
                <el-select
                  :disabled="form.checkStatus == 1"
                  clearable
                  v-model="form.gradeId"
                  placeholder="请点击班级"
                  style="width: 9.8vw"
                >
                  <el-option
                    v-for="(item, index) in gradeSource"
                    :value="item.gradeId"
                    :label="item.gradeName"
                    :key="index"
                  ></el-option>
                </el-select>

                <el-select
                  :disabled="form.checkStatus == 1"
                  v-model="form.sex"
                  placeholder="请点击性别"
                  style="width: 9.8vw; margin-left: 0.4vw"
                >
                  <!-- <el-option label="男" value="1"  style='display:none'></el-option>
                  <el-option label="女" value="2"  style='display:none'></el-option> -->
                  <el-option label="全性别" value="3"></el-option>
                </el-select>
              </el-form-item>
            </div>

            <div>
              <el-form-item label="上传图片" prop="cover">
                <el-upload
                  :disabled="form.checkStatus == 1"
                  class="upload-demo"
                  drag
                  :show-file-list="false"
                  :on-success="picUpload"
                  :before-upload="beforeUpload"
                  :action="$env.BASE_URL + '/homework/zhty/public/import_file'"
                  multiple
                  :headers="{
                    'access-token': $store.state.user.TOKEN,
                  }"
                >
                  <img
                    style="
                      width: auto;
                      height: auto;
                      max-height: 100%;
                      max-width: 100%;
                    "
                    v-if="form.cover"
                    :src="$store.state.user.BASE_URL + form.cover"
                    alt=""
                  />
                  <!-- <div v-if="!form.cover">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">
                      将文件拖到此处，或<span class="cishis">点击上传</span>
                    </div>
                  </div> -->
                  <i class="el-icon-upload" v-if="!form.cover"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>

                  <div  class="el-upload__tip" slot="tip">
                    建议上传jpg/png文件，建议不超过500kb
                  </div>
                </el-upload>
              </el-form-item>
            </div>
          </div>
          <div class="flexbox">
            <div class="box">
              <el-form-item label="简介" prop="tips" style="margin-top: -4vh">
                <el-input
                  type="textarea"
                  v-model="form.tips"
                  resize="none"
                ></el-input>
              </el-form-item>
            </div>

            <div class="div">
              <!-- 视频 -->
              <el-form-item label="上传视频" prop="video" style="width: 80%">
                <el-upload
                  :disabled="form.checkStatus == 1"
                  class="upload-demo"
                  drag
                  :action="$env.BASE_URL + '/homework/zhty/public/import_file'"
                  v-bind:on-progress="uploadVideoProcess"
                  v-bind:on-success="handleVideoSuccess"
                  v-bind:before-upload="beforeUploadVideo"
                  v-bind:show-file-list="false"
                  :headers="{
                    'access-token': $store.state.user.TOKEN,
                  }"
                >
                  <!-- <div v-if="!form.video">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将视频拖到此处，或<em>点击上传</em>
              </div>
            </div> -->
                  <video
                    style="max-height: 100%; max-width: 100%"
                    v-if="form.video != '' && !videoFlag"
                    v-bind:src="$store.state.user.BASE_URL + form.video"
                    class="avatar video-avatar"
                    controls="controls"
                  >
                    您的浏览器不支持视频播放
                  </video>
                  <div v-else-if="form.video == '' && !videoFlag">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                  </div>

                  <el-progress
                  style="margin-top: 1vh"
                    width="80"
                    v-if="videoFlag == true"
                    type="circle"
                    v-bind:percentage="videoUploadPercent"
                  ></el-progress>
                </el-upload>

                <p class="Upload_pictures">
                  <span>最多可以上传1个视频，建议大小50M，推荐格式mp4</span>
                </p>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="back" size="small" style="margin-left: 40vw"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            style="margin-left: 2vw"
            @click="add"
            >确 定</el-button
          >
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import incrementCourse from "@/views/layoutHeader/createCourse/component/incrementCourse";
import selectSchoolSource from "@/views/layoutHeader/createCourse/component/selectSchoolSource";
import {
  // 上传学习作业列表
  getjoblist,
  //  上传学习作业保存接口
  getjsaveinterface,
  //  上传学习作业详情
  getjobdetails,
} from "@/api/uploadand/index";
import { gradeList } from "@/api/school/grade";
export default {
  data() {
    return {
      shoagg: false,
      forbiddenshow: false,
      footerShow: true,
      footerShowadd: true,
      title: "上传学习作业",
      dialogVisible: false,
      input2: "",
      gradeSource: [],
      total: -1,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      tableData: [],
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: "",
      //进度条的进度，
      isShowUploadVideo: false,
      rules: {
        // 作业名称
        taskName: [
          {
            required: true,
            message: "请输入作业名称",
            trigger: "blur",
          },
        ],
        // 适合班级
        gradeId: [
          {
            required: true,
            message: "请输入适合班级",
            trigger: "blur",
          },
        ],
        // 简介
        tips: [
          {
            required: true,
            message: "请输入简介",
            trigger: "blur",
          },
        ],
        //  图片
        cover: [
          {
            required: true,
            message: "请输入图片",
            trigger: "blur",
          },
        ],
        // 视频
        video: [
          {
            required: true,
            message: "请上传视频",
            trigger: "blur",
          },
        ],
      },
      form: {
        gradeName: "",
        taskName: "",
        gradeId: "",
        sex: "",
        cover: "",
        video: "",
        tips: "",
        taskId: "",
        checkStatus: "",
        checkInfo: "",
      },
    };
  },
  created() {
    this.getjoblists();
    this.getGradeList();
  },
  methods: {
    //  照片上传
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
      }
      return types.includes(fileSuffix);
    },
    // 上传图片成功的函数
    picUpload(e, file) {
      if (e.code === 200) {
        this.form.cover = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.$refs.ruleForm.validate(() => {});
      this.loading = false;
    },
    // 视频上传
    beforeUploadVideo(file) {
      var fileSize = file.size / 1024 / 1024 < 50; //控制大小  修改50的值即可
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "video/mov",
        ].indexOf(file.type) == -1 //控制格式
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!fileSize) {
        this.$message.error("视频大小不能超过50MB");
        return false;
      }
      this.isShowUploadVideo = false;
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    //上传成功回调

    handleVideoSuccess(res, file) {
      this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;

      //后台上传数据
      if (res.code == 200) {
        this.form.video = res.result.pic; //上传成功后端返回视频地址 回显
        this.$refs.ruleForm.validate(() => {});
      } else {
        this.$message.error("上传失败！");
      }
    },

    getGradeList() {
      gradeList({ schoolId: this.$store.state.user.USER_INFO.pscShId }).then(
        (response) => {
          if (response.code === 200) {
            this.gradeSource = response.result;
          }
        }
      );
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 2) {
        return "warning-row";
      } else if (rowIndex === 4) {
        return "success-row";
      }
      return "";
    },
    getjoblists() {
      let data = {
        userId: this.$store.state.user.USER_INFO.id,
        ...this.page,
      };
      getjoblist(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result;
          this.total = res.total;
        }
      });
    },
    //上传学习作业保存
    showAdd() {
      this.shoagg = true;
      this.footerShow = true;
      this.forbiddenshow = false;
      this.form = {
        taskName: "",
        gradeId: "",
        sex: "",
        cover: "",
        video: "",
        tips: "",
        taskId: "",
        checkStatus: "",
        checkInfo: "",
      };
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    // 确定保存
    add() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.disable = true;
          let data = {
            ...this.form,
          };
          getjsaveinterface(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功!");
              this.dialogVisible = false;
              this.$router.back();
              // this.getjoblists();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    close(key) {
      this[key] = false;
    },

    back() {
      this.$router.push({
        path: "sportwork",
        query: {
          show: 2,
        },
        
      });
    },
  },
  components: {
    incrementCourse,
    selectSchoolSource,
  },
};
</script>

<style lang="scss" scoped>
.el-form-item ::v-deep .el-form-item__error {
  position: relative;
}
.flexbox {
  display: flex;
}
::v-deep .el-upload__text {
  font-size: 0.4vw;
  margin-top: -2vh;
}
.Upload_pictures {
  font-size: 0.486vw;
  color: #606266;
  margin-top: -2vh;
  white-space: nowrap;
}
::v-deep .el-upload__tip {
  margin-top: -2vh;
}
::v-deep .el-upload-dragger .el-icon-upload {
  margin: 1.1vh 0 1.6vh;
}
::v-deep .el-upload-dragger {
  width: 20vw;
  height: 12vh;
}

::v-deep .el-upload-dragger .el-icon-upload {
  font-size: 1.5vw;
  line-height: 5vh;
}
::v-deep .el-textarea__inner {
  width: 20vw;
  height: 16.5vh;
}
::v-deep .el-upload .el-upload--text {
  width: 20vw;
}
.createCource {
  width: 80vw;
  margin: auto;
  .course-top {
    display: flex;
    justify-content: space-between;
    padding: 1vh 0;
    ::v-deep .el-breadcrumb__inner {
      font-size: 1vw;
    }
    .top-right {
      font-size: 1vw;
      color: #1677ff;
    }
  }
  .course-form {
    height: 80vh;
    max-height: 80vh;
    overflow-y: auto;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    ::v-deep .el-radio {
      margin: 0.65vw;
    }
  }
}
</style>
